﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using OpenPasteSpider.projectmodel;
using Volo.Abp.DependencyInjection;
using Z.EntityFramework.Plus;

namespace OpenPasteSpider
{
    /// <summary>
    /// 执行命令队列的服务
    /// </summary>
    public class CommandTaskHandler : ISingletonDependency
    {

        /// <summary>
        /// 
        /// </summary>
        private readonly ILogger<CommandTaskHandler> _logger;

        /// <summary>
        /// 
        /// </summary>
        private IServiceProvider _serviceprovider;

        /// <summary>
        /// 
        /// </summary>
        private ActionHelper _actionhelper;

        /// <summary>
        /// 
        /// </summary>
        private SpiderConfig _config;


        /// <summary>
        /// 
        /// </summary>
        private readonly ChannelHelper _channelHelper;

        /// <summary>
        /// 
        /// </summary>
        private readonly PublicModelHelper _modelHelper;

        /// <summary>
        /// 
        /// </summary>
        private readonly IHttpClientFactory _client;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="serviceprovider"></param>
        /// <param name="config"></param>
        /// <param name="manageHelper"></param>
        /// <param name="httpClientFactory"></param>
        /// <param name="channelHelper"></param>
        /// <param name="modelHelper"></param>
        public CommandTaskHandler(
            ILogger<CommandTaskHandler> logger,
            IServiceProvider serviceprovider,
            IOptions<SpiderConfig> config,
            ActionHelper manageHelper,
            IHttpClientFactory httpClientFactory,
            ChannelHelper channelHelper,
            PublicModelHelper modelHelper)
        {
            _logger = logger;
            _actionhelper = manageHelper;
            _serviceprovider = serviceprovider;
            _config = config.Value;
            _channelHelper = channelHelper;
            _modelHelper = modelHelper;
            _client = httpClientFactory;
        }


        /// <summary>
        /// 根据GUID获取任务队列
        /// </summary>
        /// <param name="id">可传可不传</param>
        /// <returns></returns>
        public async Task<int> DoCommandPlanAsync(int id)
        {
            using var scop = _serviceprovider.CreateScope();
            using var _dbContext = scop.ServiceProvider.GetRequiredService<IOpenPasteSpiderDbContext>();
            var _plan = await _dbContext.PlanInfo.Where(x => x.Id == id).AsNoTracking().FirstOrDefaultAsync();
            if (_plan != null && _plan != default)
            {
                if (_plan.State == RunState.waitrun)
                {
                    //变更状态，运行这个任务中
                    _dbContext.PlanInfo.Where(x => x.Id == _plan.Id).Update(x => new PlanInfo() { State = RunState.running });
                    var linuxdto = await _modelHelper.ItemLinuxInfo(_plan.LinuxId, _dbContext);
                    var _pitems = await _dbContext.PlanItem.Where(x => x.PlanInfoId == id).OrderBy(x => x.RunIndex).AsNoTracking().ToListAsync();
                    var _stop = new Stopwatch();
                    _stop.Start();
                    var _boolbreak = false;
                    string _result = String.Empty;
                    if (_pitems != null && _pitems.Count > 0)
                    {
                        _dbContext.AttachRange(_pitems);
                    }
                    foreach (var item in _pitems)
                    {
                        _result = await doCommand(item, _dbContext, _plan, _result, linuxdto);
                        _dbContext.SaveChanges();
                        if (_plan.OrderModel == OrderModel.daemonupdate)
                        {
                            if (item.ActionType == ActionState.daemonpulltry)
                            {
                                if (item.ExecState == RunState.success)
                                {
                                    _boolbreak = false;
                                    break;
                                }
                            }
                        }
                        if (item.ExecState == RunState.failed && item.StrictMode)
                        {
                            _logger.LogError($"=== == === {item.Command} {item.ActionType.ToString()}");
                            _boolbreak = true;
                            break;
                        }
                    }
                    //如果当前服务所在服务器，被重启等，则命令会失效或者中断... .. .
                    if (_boolbreak) { _plan.State = RunState.failed; } else { _plan.State = RunState.success; }
                    _stop.Stop();
                    _plan.Durtion = (int)_stop.Elapsed.TotalSeconds;
                    await _dbContext.PlanInfo.Where(x => x.Id == _plan.Id).UpdateAsync(x => new PlanInfo()
                    {
                        State = _plan.State,
                        Durtion = _plan.Durtion
                    });
                    await _dbContext.SaveChangesAsync();
                    //根据结果统计数据
                    await CollectNumber(_plan, _dbContext);
                    var _query = from a in _dbContext.PlanInfo.Where(x => x.Id == _plan.Id)
                                 join b in _dbContext.ProjectInfo on a.ProjectId equals b.Id into c
                                 from d in c.DefaultIfEmpty()
                                 join e in _dbContext.ServiceInfo on a.ServiceId equals e.Id into g
                                 from h in g.DefaultIfEmpty()
                                 join m in _dbContext.ModelInfo on a.ModelId equals m.Id into j
                                 from i in j.DefaultIfEmpty()
                                 join k in _dbContext.LinuxInfo on a.LinuxId equals k.Id into n
                                 from l in n.DefaultIfEmpty()
                                 select new
                                 {
                                     pname = d != null ? d.Name : "",
                                     sname = h != null ? h.Name : "",
                                     mcode = i != null ? i.Code : "",
                                     model = i,
                                     project = d,
                                     lname = l != null ? l.Name : ""
                                 };
                    var find = await _query.FirstOrDefaultAsync();
                    if (find != null && find != default)
                    {
                        var sbnotice = new StringBuilder("");
                        sbnotice.AppendLine($"- -- ---任务[通知]报告--- -- -");
                        //sbnotice.AppendLine($"任务类型：{_plan.OrderModel.ToString()}");
                        sbnotice.AppendLine($"任务类型：{_plan.OrderModel.ToString()}");
                        sbnotice.AppendLine($"服  务  器：{_plan.LinuxId} {find.lname}");
                        sbnotice.AppendLine($"所在项目：{_plan.ProjectId} {find.pname}");
                        sbnotice.AppendLine($"目标服务：{_plan.ServiceId} {find.sname}");
                        sbnotice.AppendLine($"操作环境：{_plan.ModelId} {find.mcode}");
                        sbnotice.AppendLine($"执行结果： -- {_plan.State.ToString()} -- ");
                        sbnotice.AppendLine($"任务耗时：{_plan.Durtion}s");
                        sbnotice.AppendLine($"任务时间：{_plan.CreateDate.ToString("yyyy-MM-dd HH:mm:ss")}");
                        _channelHelper.WriteSlaveNotice(new SlaveNoticeItem()
                        {
                            Code = _plan.OrderModel.ToString(),
                            Body = sbnotice.ToString()
                        });
                    }
                }
            }
            return 1;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="plan"></param>
        /// <param name="_dbContext"></param>
        /// <returns></returns>
        private async Task<bool> CollectNumber(PlanInfo plan, IOpenPasteSpiderDbContext _dbContext)
        {
            if (plan.ModelId != 0)
            {
                if (plan.State == RunState.success)
                {
                    switch (plan.OrderModel)
                    {
                        case OrderModel.resize:
                            await _dbContext.ModelInfo.Where(x => x.Id == plan.ModelId).UpdateAsync(x => new ModelInfo { NumResize = x.NumResize + 1 });
                            break;
                        case OrderModel.buildimage:
                            await _dbContext.ServiceInfo.Where(x => x.Id == plan.ServiceId).UpdateAsync(x => new ServiceInfo { NumBuild = x.NumBuild + 1 });
                            break;
                        case OrderModel.update:
                            await _dbContext.ModelInfo.Where(x => x.Id == plan.ModelId).UpdateAsync(x => new ModelInfo { NumUpdate = x.NumUpdate + 1 });
                            break;
                    }
                }
                if (plan.State == RunState.failed)
                {
                    switch (plan.OrderModel)
                    {
                        case OrderModel.resize:
                            await _dbContext.ModelInfo.Where(x => x.Id == plan.ModelId).UpdateAsync(x => new ModelInfo { NumResize = x.NumResize + 1, NumFailedResize = x.NumFailedResize + 1 });
                            break;
                        case OrderModel.buildimage:
                            await _dbContext.ServiceInfo.Where(x => x.Id == plan.ServiceId).UpdateAsync(x => new ServiceInfo { NumBuild = x.NumBuild + 1, NumBuildFailed = x.NumBuildFailed + 1 });
                            break;
                        case OrderModel.update:
                            await _dbContext.ModelInfo.Where(x => x.Id == plan.ModelId).UpdateAsync(x => new ModelInfo { NumUpdate = x.NumUpdate + 1, NumFailedUpdate = x.NumFailedUpdate + 1 });
                            break;
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 执行未完成的任务 需要改版 传入slavename
        /// </summary>
        public async Task<bool> DoUnFinishPlanAsync(IOpenPasteSpiderDbContext _dbContext, string slavename = "")
        {
            var _plan = await _dbContext.PlanInfo.Where(x => x.State == RunState.running).WhereIf(!String.IsNullOrEmpty(slavename), x => _dbContext.LinuxInfo.Where(x => x.SlaveName == slavename).Select(x => x.Id).Contains(x.LinuxId)).OrderByDescending(x => x.Id).AsNoTracking().FirstOrDefaultAsync();
            if (_plan != null && _plan != default)
            {
                if (_plan.OrderModel == OrderModel.addregistry)
                {
                    var _plans = await _dbContext.PlanItem.Where(x => x.PlanInfoId == _plan.Id).OrderBy(x => x.RunIndex).AsNoTracking().ToListAsync();
                    var linuxdto = await _modelHelper.ItemLinuxInfo(_plan.LinuxId, _dbContext);
                    var _stop = new Stopwatch();
                    _stop.Start();
                    var _boolbreak = false;
                    string _result = String.Empty;
                    for (var i = 0; i < _plans.Count; i++)
                    {
                        var item = _plans[i];
                        if (item.ActionType != ActionState.daemonreload && item.ExecState == RunState.waitrun)
                        {
                            _result = await doCommand(item, _dbContext, _plan, _result, linuxdto);
                            await _dbContext.PlanItem.Where(x => x.Id == item.Id).UpdateAsync(x => new PlanItem()
                            {
                                ExecState = item.ExecState,
                                ActionResult = item.ActionResult,
                                Durtion = item.Durtion
                            });

                            if (item.ExecState == RunState.failed && item.StrictMode)
                            {
                                _logger.LogError($"=== == === {item.Command} {item.ActionType.ToString()}");
                                _boolbreak = true;
                                break;
                            }
                        }

                    }
                    //如果当前服务所在服务器，被重启等，则命令会失效或者中断... .. .
                    if (_boolbreak) { _plan.State = RunState.failed; } else { _plan.State = RunState.success; }
                    _stop.Stop();
                    await _dbContext.PlanInfo.Where(x => x.Id == _plan.Id).UpdateAsync(x => new PlanInfo()
                    {
                        State = _plan.State,
                        Durtion = (int)_stop.Elapsed.TotalSeconds
                    });

                    _modelHelper.PlanRunComplete(_plan);

                }
            }

            return true;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="item"></param>
        /// <param name="_dbContext"></param>
        /// <param name="info"></param>
        /// <param name="_tempresponse"></param>
        /// <returns></returns>
        private async Task<string> doCommand(PlanItem item, IOpenPasteSpiderDbContext _dbContext, PlanInfo info, string _tempresponse, LinuxInfoDto _linux)
        {
            _logger.LogInformation($"=={DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}==exec sum command {item.RunIndex} {item.ActionType.ToString()}");
            var tick = new Stopwatch();
            tick.Start();
            item.ExitCode = 0;
            item.ExecState = RunState.success;

            try
            {
                switch (item.ActionType)
                {
                    case ActionState.dockerstop:
                    case ActionState.dockerbuild:
                    case ActionState.dockertag:
                    case ActionState.custom://前置或者后置命令
                        {
                            var bodyStr = await _actionhelper.RunCommandAsync(item.Command, info.LinuxId);
                            if (bodyStr.ok)
                            {
                                item.ActionResult = bodyStr.msg;
                                item.ExecState = RunState.success;
                            }
                            else
                            {
                                item.ActionResult = bodyStr.msg;
                                item.ExecState = RunState.failed;
                            }
                        }
                        break;
                    case ActionState.dockerrm:
                        {
                            var bodyStr = await _actionhelper.RunCommandAsync(item.Command, info.LinuxId);
                            if (bodyStr.ok)
                            {
                                item.ActionResult = bodyStr.msg;
                                item.ExecState = RunState.success;
                                if (item.AppId != 0)
                                {
                                    await _dbContext.AppInfo.Where(x => x.Id == item.AppId).UpdateAsync(x => new AppInfo() { StateCode = RunState.delete });
                                    await _modelHelper.ItemAppClean(item.AppId);
                                }
                            }
                            else
                            {
                                item.ActionResult = bodyStr.msg;
                                item.ExecState = RunState.failed;
                            }

                        }
                        break;
                    case ActionState.linuxcacheclean:
                        {
                            //单个环境升级
                            await _actionhelper.LinuxCleanCache(info.LinuxId);
                            item.ActionResult = "服务器缓存清理完成";
                        }
                        break;
                    case ActionState.checklinuxfree:
                        {
                            //检查服务器的可用资源 内存情况
                            var runinfo = await _actionhelper.GetLinuxState(info.LinuxId);
                            if (runinfo != null && runinfo != default)
                            {
                                var linuxinfo = _dbContext.LinuxInfo.Where(x => x.Id == info.LinuxId).AsNoTracking().FirstOrDefault();
                                if (linuxinfo != null && linuxinfo != default)
                                {
                                    if (runinfo.MemoryFree <= linuxinfo.FreeMemory)
                                    {
                                        item.ExecState = RunState.failed;
                                        item.ExitCode = -1;
                                        item.ActionResult = "服务器可用内存资源不足！";
                                    }
                                }
                            }
                        }
                        break;
                    case ActionState.waitdely:
                        {
                            for (var i = 0; i < _config.WaitNginxLoadTime; i++)
                            {
                                await Task.Delay(1000);
                            }
                            item.ExecState = RunState.success;
                        }
                        break;
                    case ActionState.dockerrun:
                        {
                            var needportnum = 0;
                            //构建-p xxx:yy命令
                            var dockerlisten = String.Empty;
                            //这里需要组合命令，是否需要分配端口等,有多少个端口等
                            var service = await _modelHelper.ItemServiceInfo(info.ServiceId, _dbContext);
                            var linux = await _modelHelper.ItemLinuxInfo(info.LinuxId, _dbContext);
                            var model = await _modelHelper.ItemModelInfoAsync(info.ModelId, _dbContext);
                            var project = await _modelHelper.ItemProjectInfo(service.Project.Id, _dbContext);
                            var app = await _modelHelper.ItemAppInfo(item.AppId, _dbContext);

                            if (service != null && service != default)
                            {
                                if (service.NeedMapping)
                                {
                                    if (!String.IsNullOrEmpty(service.ListenPorts))
                                    {
                                        needportnum = service.ListenPorts.Split(',').Length;
                                    }
                                    if (needportnum == 0)
                                    {
                                        item.ExecState = RunState.failed;
                                        item.ActionResult = "Service的配置信息有误，需要映射端口，然后监听端口为空！";
                                    }
                                }
                            }
                            else
                            {
                                item.ExecState = RunState.failed;
                                item.ActionResult = "Service信息不存在";
                                return item.ActionResult;
                            }
                            if (needportnum > 0)
                            {

                                if (linux == null || linux == default)
                                {
                                    item.ExecState = RunState.failed;
                                    item.ActionResult = "linux信息不存在";
                                    return item.ActionResult;
                                }
                                var useds = await _actionhelper.GetUsedPorts(linux.Id);
                                var ports = _actionhelper.CountCanUsePort(linux.OpenPorts, needportnum, useds.ToArray());
                                if (ports.Length != needportnum)
                                {
                                    item.ExecState = RunState.failed;
                                    item.ActionResult = "可使用的映射端口不足，请查看可对外端口，或者修改成局域网模式！";
                                }
                                var temports = service.ListenPorts.Split(',');
                                for (var i = 0; i < temports.Length; i++)
                                {
                                    dockerlisten += $" -p {ports[i]}:{temports[i]}";
                                }
                                app.OutPort = string.Join(',', ports);
                                await _dbContext.AppInfo.Where(x => x.Id == item.AppId).UpdateAsync(x => new AppInfo() { OutPort = app.OutPort });
                                await _modelHelper.ItemAppClean(item.AppId);
                            }

                            if (info.ModelId == 0)
                            {
                                item.ExecState = RunState.failed;
                                item.ActionResult = "ModelId为0，配置错误";
                                return item.ActionResult;
                            }

                            var runstring = new System.Text.StringBuilder($"docker run -d{(service.AutoRestart ? " --restart=always" : "")}");

                            runstring.Append($" -e \"RunConfig:Model={model.Code}\"");


                            //设定容器名称
                            var lenless = 32 - $"{model.Code}_{item.AppId}".Length - 1;
                            app.Name = $"{model.Code}_{info.ServiceId}_{Guid.NewGuid().ToString().Replace("-", "").ToLower().Substring(0, lenless)}";
                            runstring.Append($" --name {app.Name}");


                            //设定环境
                            if (!String.IsNullOrEmpty(service.OtherArgs))
                            {
                                runstring.Append($" {_modelHelper.BuildCommandString(service.OtherArgs, _linux: linux, _project: project, _service: service, _model: model, _app: app)}");
                            }

                            if (service.FileModel != 3)
                            {
                                if (_linux != null && _linux != default && _linux.Tool == "podman")
                                {
                                    runstring.Append($"{dockerlisten} localhost/{service.Project.Code}_{service.Code}:{info.Version}");
                                }
                                else
                                {
                                    runstring.Append($"{dockerlisten} {service.Project.Code}_{service.Code}:{info.Version}");
                                }
                            }
                            else
                            {
                                runstring.Append($"{dockerlisten} {service.DirectImage}");
                            }
                            if (!String.IsNullOrEmpty(service.EnvironmentArgs))
                            {
                                runstring.Append($" {_modelHelper.BuildCommandString(service.EnvironmentArgs, _linux: linux, _project: project, _service: service, _model: model, _app: app)}");
                            }
                            //计算配置中心的值 -e "key=val"
                            var bodyStr = await _actionhelper.RunCommandAsync(runstring.ToString(), info.LinuxId);
                            if (bodyStr.ok)
                            {
                                if (!String.IsNullOrEmpty(bodyStr.msg))
                                {
                                    if (bodyStr.msg.Length > 12)
                                    {
                                        var appid = bodyStr.msg.Substring(0, 12);
                                        await _dbContext.AppInfo.Where(x => x.Id == item.AppId).UpdateAsync(x => new AppInfo() { AppID = appid });
                                        item.ActionResult = bodyStr.msg;
                                    }
                                    else
                                    {
                                        item.ActionResult = bodyStr.msg;
                                        item.ExecState = RunState.failed;
                                    }
                                }
                                else
                                {
                                    item.ActionResult = bodyStr.msg;
                                    item.ExecState = RunState.failed;
                                }
                            }
                            else
                            {
                                item.ExecState = RunState.failed;
                                item.ActionResult = bodyStr.msg;
                            }
                        }
                        break;

                    case ActionState.dockerrmi:
                        {
                            var boolexits = true;
                            if (!String.IsNullOrEmpty(item.Target))
                            {
                                var command = await _actionhelper.RunCommandAsync($"docker inspect {item.Target}", info.LinuxId);
                                if (!command.ok)
                                {
                                    boolexits = false;
                                    item.ActionResult = $"镜像{item.Target} 未找到！";
                                }
                            }
                            if (boolexits)
                            {
                                var command = await _actionhelper.RunCommandAsync(item.Command, info.LinuxId);
                                if (!command.ok)
                                {
                                    item.ExecState = RunState.failed;
                                    item.ActionResult = $"镜像{item.Target} 不存在";
                                }
                            }
                        }
                        break;

                    case ActionState.sqlrun:
                        {
                            if (item.AppId != 0)
                            {
                                await _dbContext.AppInfo.Where(x => x.Id == item.AppId).UpdateAsync(x => new AppInfo() { StateCode = RunState.running });
                                await _modelHelper.ItemAppClean(item.AppId);
                            }
                        }
                        break;
                    case ActionState.sqlstop:
                        {
                            if (item.AppId != 0)
                            {
                                await _dbContext.AppInfo.Where(x => x.Id == item.AppId).UpdateAsync(x => new AppInfo() { StateCode = RunState.prestop });
                                await _modelHelper.ItemAppClean(item.AppId);
                            }
                        }
                        break;
                    case ActionState.imageexist:
                        {
                            var result = await _actionhelper.CheckImageExists(item.Command, info.LinuxId);
                            if (!result)
                            {
                                item.ExecState = RunState.failed;
                                item.ActionResult = "镜像不存在";
                            }
                            else
                            {
                                item.ActionResult = "镜像存在";
                            }
                            if (!String.IsNullOrEmpty(item.Target))
                            {
                                if (int.TryParse(item.Target, out var _varsion))
                                {
                                    _dbContext.BindServiceImage.Where(x => x.ServiceId == info.ServiceId && x.Version == _varsion && x.BuildState == RunState.waitrun).Update(x => new BindServiceImage { IsEnable = true, BuildState = result ? RunState.success : RunState.failed });
                                }
                            }
                        }
                        break;
                    case ActionState.dockerpull:
                        {
                            if (!await _actionhelper.CheckImageExists(item.Command, info.LinuxId))
                            {
                                item.ExecState = RunState.failed;
                                item.ActionResult = "镜像不存在";
                            }
                            else
                            {
                                item.ActionResult = "镜像已经存在，不需要拉取";
                            }
                        }
                        break;

                    case ActionState.dockerwaitrun://等待docker run起来
                        {
                            if (item.AppId == 0)
                            {
                                item.ExecState = RunState.failed;
                                item.ActionResult = "目标AppInfo.Id错误，不能为0";
                            }
                            else
                            {
                                await Task.Delay(3000);
                                var appinfoitem = await _dbContext.AppInfo.Where(x => x.Id == item.AppId).AsNoTracking().FirstOrDefaultAsync();
                                if (appinfoitem != null && appinfoitem != default)
                                {
                                    if (!String.IsNullOrEmpty(appinfoitem.AppID))
                                    {
                                        var boolrun = false;
                                        for (var i = 0; i < _config.WaitRunTime; i++)
                                        {
                                            await Task.Delay(1000);
                                            var dockerrun = await _actionhelper.GetDockerPsGrep(appinfoitem.AppID, info.LinuxId);
                                            if (dockerrun.run)
                                            {
                                                var dockerinfo = await _actionhelper.GetDockerInspect(appinfoitem.AppID, info.LinuxId);
                                                if (dockerinfo != null)
                                                {
                                                    if (dockerinfo.Status == "running" && dockerinfo.RestartCount == 0)
                                                    {
                                                        boolrun = true;
                                                        await _dbContext.AppInfo.Where(x => x.Id == item.AppId).UpdateAsync(x => new AppInfo() { Address = dockerinfo.IPAddress, Name = dockerinfo.Name });
                                                        item.ActionResult = $"ID:{appinfoitem.AppID} Name:{dockerinfo.Name} Address:{dockerinfo.IPAddress}";
                                                        break;
                                                    }
                                                    else
                                                    {
                                                        item.ExecState = RunState.failed;
                                                        item.ActionResult = "启动异常，检查日志查看结果!";
                                                        break;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                await Task.Delay(1000);
                                                continue;
                                            }
                                        }
                                        if (!boolrun)
                                        {
                                            item.ExecState = RunState.failed;
                                            item.ActionResult = $"docker container name: {item.Command} 没有正确启动！";
                                        }
                                    }
                                    else
                                    {
                                        item.ExecState = RunState.failed;
                                        item.ActionResult = "目标AppInfo.APPID错误，信息未能找到";
                                    }
                                }
                                else
                                {
                                    item.ExecState = RunState.failed;
                                    item.ActionResult = "目标AppInfo错误，信息未能找到";
                                }
                            }
                        }
                        break;
                    case ActionState.buildupdate:
                        {
                            //单个环境升级
                            if (info.ModelId != 0)
                            {
                                await _actionhelper.ModelUpdate(_dbContext, info.ModelId);
                                item.ActionResult = "添加自动升级任务成功";
                            }
                            else
                            {
                                item.ExecState = RunState.failed;
                            }
                        }
                        break;
                    case ActionState.buildupdates:
                        {
                            if (!String.IsNullOrEmpty(item.Command))
                            {
                                foreach (var _code in item.Command.Split(','))
                                {
                                    if (!String.IsNullOrEmpty(_code))
                                    {
                                        var modelitem = await _modelHelper.ReadModelInfoByServiceIdAsync(info.ServiceId, _code, _dbContext);
                                        if (modelitem != null && modelitem != default)
                                        {
                                            await _actionhelper.ModelUpdate(_dbContext, modelitem.Id, info.Version);
                                        }
                                    }
                                }
                                item.ActionResult = "添加自动升级任务成功";
                                item.ExecState = RunState.success;
                            }
                            else
                            {
                                if (info.ModelId != 0)
                                {
                                    await _actionhelper.ModelUpdate(_dbContext, info.ModelId, info.Version);
                                    item.ActionResult = "添加自动升级任务成功";
                                    item.ExecState = RunState.success;
                                }
                                else
                                {
                                    item.ActionResult = "command中没有附带有效的环境信息";
                                    item.ExecState = RunState.failed;
                                }
                            }
                        }
                        break;
                    case ActionState.buildnotify:
                        {
                            //构建成功后的通知 外部通知了
                            //_channelHelper.WriteSlaveNotice(new SlaveNoticeItem() { Code = "servicebuild", Body = $"{item.Command}", ObjId = info.ServiceId });
                            item.ExecState = RunState.success;
                            item.ActionResult = "推送构建成功的通知！";

                        }
                        break;

                    default:
                        item.ActionResult = $"未知的执行命令:{item.ActionType.ToString()}";
                        item.ExecState = RunState.notfound;
                        break;
                }
            }
            catch (Exception exl)
            {
                _logger.LogException(exl, LogLevel.Error);
                item.ActionResult = exl.Message;
                item.ExecState = RunState.failed;
            }
            finally
            {
                tick.Stop();
                item.Durtion = (int)tick.Elapsed.TotalSeconds;
            }
            return item.ActionResult;
        }

    }
}
